# -*- coding: utf-8 -*-
"""
Created on 2025/2/20 17:57
---------
@summary: 这个Excel之负责写  不负责读取
---------
@author: rui_kai
"""
from xlsxwriter import Workbook


class ExcelHandlerNew:
    SHEET_NAME = "Sheet1"

    def __init__(self, file_path):
        self.file_path = file_path
        self.workbook = Workbook(file_path)
        self.workbook.strings_to_urls = False  # 这一步很关键，解决了URL超过65535行没了
        self.sheet = self.workbook.add_worksheet(self.SHEET_NAME)
        self.rows = 0

    def write_head(self, head):
        self.sheet.write_row(0, 0, head)
        self.rows += 1

    def write_row(self, value, col: int = 0):
        """
        写入一行数据
        :param value:
        :param col:
        :return:
        """
        self.sheet.write_row(self.rows, col, value)
        self.rows += 1

    def save(self):
        """
        保存并关闭 Excel 文件。
        """
        if self.workbook:
            self.workbook.close()
            self.workbook = None  # 关闭后置空，防止重复操作
            self.file_path = None  # 重置路径


class ExcelHandler:
    SHEET_NAME = "Sheet1"
    _instance = None  # 单例实例引用
    _initialized = False  # 标记是否已初始化
    IS_WRITE = False  # 是否已经写入了

    def __init__(self):
        if not self._initialized:
            self.file_path = None
            self.workbook = None
            self.sheet = None
            self.rows = 0
            self.cols = 0
            self._initialized = True

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def pipline_init(self, file_path):
        if self.file_path:
            return

        self.file_path = file_path
        self.workbook = Workbook(file_path)
        self.workbook.strings_to_urls = False  # 这一步很关键，解决了URL超过65535行没了
        self.sheet = self.workbook.add_worksheet(self.SHEET_NAME)

    def write_header(self, file_path, headers: list):
        """
        写头
        :param file_path:
        :param headers:
        :return:
        """
        self.pipline_init(file_path)
        self.sheet.write_row(0, 0, headers)
        self.rows += 1
        # self.save()

    def write_row(self, value, col: int = 0):
        """
        写入一行数据
        :param value:
        :param col:
        :return:
        """
        self.IS_WRITE = True
        self.sheet.write_row(self.rows, col, value)
        self.rows += 1

    def save(self):
        """
        保存并关闭 Excel 文件。
        """
        if self.workbook:
            self.workbook.close()
            self.workbook = None  # 关闭后置空，防止重复操作
            self.file_path = None  # 重置路径


if __name__ == '__main__':
    e = ExcelHandler()
    e.pipline_init("1.xlsx")
    # e.write_header("1.xlsx", ["name", "age"])
    e.write_row(["name", "age"])
    e.write_row(["name", "age"])
    e.write_row(["name", "age"])
    e.write_row(["name", "age"])
    e.write_row(["name", "age"])
    e.write_row(["name", "age"])
    # e.save()
